/**
 * Script used to obtain the list of medias, users, and the status of the music (playing or not)
 */
$(document).ready(
		doPoll(true)
);

/**
 * Update the web page
 * @param boolean True if infinite loop, False for once
 */
function doPoll(boolean){
	$.ajax({
	    dataType: "json",
	    url: 'poll',
	    timeout: 60000,
	    success: function(data, textStatus, jqXHR) {
			$("#pwd").text(data["guest_password"]); // Guest password
			if (data["is_user_connected"]) {
				console.log("User connected. Polling...");
				var is_admin = data["is_admin"];
				var is_playing = data["is_playing"];
				$("#play_link").attr("href", is_playing ? "console?action=pause" : "console?action=play");
				$("#play_link").attr("title", is_playing ? "Pause" : "Play");
				$("#play_button").attr("src", is_playing ? "resources/images/pause.png" : "resources/images/play.png");
				$("#play_button").attr("alt", is_playing ? "Pause" : "Play");
	
				var media_list = data["media_list"];
				var admin_list = data["admin_list"];
				var guest_list = data["guest_list"];
				createMediaUL(media_list,$("#playlist ul"),is_admin);
	
				createUserUL(admin_list,$("#lists > h2:first-child + ul"));
				createUserUL(guest_list,$("#lists > h2:not(:first-child) + ul"));
				if (boolean) setTimeout(function() {doPoll(true);}, 5000);
			}
			else {
				console.log("User not connected. Polling stopped.");
				alert("You've been disconnected due to inactivity.");
			}
	    },
	    error: function(jqXHR, textStatus, errorThrown) {
			 console.log("Request Failed: " + textStatus);
			 alert("Server seems offline.");
		}
	});
}

/**
 * Creates an html ul (media) from an array
 * @param array The array where data are stored
 * @param ul The targeted ul
 * @param True if the user that creates the ul is an admin (so he can see red cross)
 */
function createMediaUL(array, ul, is_admin) {
	ul.empty();
	$.each(array, function(key, val) {
		var el = $(document.createElement('li')).append($(document.createElement('div')).text(val['toString']));
		if (is_admin)
			el.append('<a href="console?action=del&media='+val["mediaName"]+'" onclick="return doAction(this);"><img src="resources/images/delete.png" alt="Delete" /></a>');

		ul.append(el);
	});
}

/**
 * Creates an html ul (user, admin or guest) from an array (given)
 * @param array The array where data are stored
 * @param ul The targeted ul
 */
function createUserUL(array, ul) {
	ul.empty();
	$.each(array, function(key, val) {
		ul.append(
				$(document.createElement('li')).text(val['name'])
		);
	});
}